#!/usr/bin/perl -w
use lib './lib';
use strict;
use Socket;
use Chimera::CGI;
use Chimera::Memcached;
use IO::Poll qw(POLLIN POLLOUT POLLHUP POLLERR);
use Errno qw(EWOULDBLOCK);

$SIG{PIPE} = 'IGNORE';

#my $memcached_port = 11211;

my $host  = $ENV{'SERVER_NAME'} = shift || die("Usage: chimera.pl host [port]\n");
my $port  = $ENV{'SERVER_PORT'} = shift || 3092;
my $proto = getprotobyname('tcp') || die("getprotobyname() failed: $!");

socket(my $sock, AF_INET, SOCK_STREAM, $proto) or die("socket() failed: $!");
setsockopt($sock, SOL_SOCKET, SO_REUSEADDR, 1) or die("can't set SO_REUSEADDR: $!");
my $pack_addr = inet_aton($host) or die("inet_aton() failed: $host");
my $sock_addr = sockaddr_in($port, $pack_addr);
bind($sock, $sock_addr) or die("bind() failed: $!");
listen($sock, SOMAXCONN) or die("listen() failed: $!");
my $poll = IO::Poll->new() or die("can't create IO::Poll object\n");
$poll->mask($sock => POLLIN|POLLOUT);

my $memcached = Chimera::Memcached->new('127.0.0.1', 3094);

warn "Waiting for incoming connections on port $port...\n";

while(1) {
    $poll->poll();
    
    for my $handle ($poll->handles(POLLIN|POLLHUP|POLLERR)) {
        if ($handle eq $sock) {
        	my $conn_addr = accept(my $conn, $sock) or die("accept() failed: $!");
        	$poll->mask($conn => POLLIN);
        } else {
    		$memcached->get('myKey1');     	
        }
    }
    
    for my $handle ($poll->handles(POLLOUT|POLLERR)) {
    }
  
}